﻿using System;
using System.Diagnostics;
using System.Windows;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Threading;

namespace Greycastle.RUBuildin.View
{
    public class BubbleWindowViewModel : ViewModelBase, IDisposable
    {
        private readonly IntPtr _watchWindowHandle;
        private ForegroundWindowWatcher _foregroundWindowWatcher;

        /// <summary>Constructs a viewmodel for the bubble window that will hide the window when given window handle is focused</summary>
        /// <param name="watchWindowHandle">The window handle to watch for, when this is in foreground the bubble window will hide</param>
        public BubbleWindowViewModel(IntPtr watchWindowHandle)
        {
            _watchWindowHandle = watchWindowHandle;
            _foregroundWindowWatcher = new ForegroundWindowWatcher();
            //_foregroundWindowWatcher.ForegroundWindowChanged += (s, e) => SetVisibilityBasedOnActiveWindow(e.NewForegroundWindow);
            //SetVisibilityBasedOnActiveWindow(ForegroundWindowWatcher.GetForegroundWindow());
            SetWindowIsVisible(true);
        }

        private void SetVisibilityBasedOnActiveWindow(IntPtr currentlyActiveWindow)
        {
            Debug.WriteLine("Watching window {0} with title '{1}'", _watchWindowHandle, ForegroundWindowWatcher.GetTitle(_watchWindowHandle));
            Debug.WriteLine("Active window {0} with title '{1}'", currentlyActiveWindow, ForegroundWindowWatcher.GetTitle(currentlyActiveWindow));

            var isInForeground = currentlyActiveWindow == _watchWindowHandle || 
                ForegroundWindowWatcher.IsChildWindowOfOf(currentlyActiveWindow, _watchWindowHandle);

            var windowIsVisible = isInForeground == false;

            DispatcherHelper.RunAsync(() => SetWindowIsVisible(windowIsVisible));
        }

        private void SetWindowIsVisible(bool visible)
        {
            Debug.WriteLine("Setting window visibility to: " + visible);
            WindowVisibility = visible ? Visibility.Visible : Visibility.Collapsed;
            RaisePropertyChanged(() => WindowVisibility);
        }

        public Visibility WindowVisibility { get; private set; }

        public void Dispose()
        {
            if (_foregroundWindowWatcher == null)
                return;

            _foregroundWindowWatcher.Dispose();
            _foregroundWindowWatcher = null;
        }
    }
}
